package de.jmda.gen.java.impl;

import java.util.ArrayList;
import java.util.List;

import javax.validation.constraints.NotNull;

import de.jmda.gen.Generator;
import de.jmda.gen.impl.AbstractCompoundGenerator;
import de.jmda.gen.java.StaticPartGenerator;
import de.jmda.gen.java.StaticPartsGenerator;

/**
 * Maintains a collection of {@link StaticPartGenerator}s.
 *
 * @author rwegner
 */
public class DefaultStaticPartsGenerator
		extends AbstractCompoundGenerator
		implements StaticPartsGenerator
{
	private @NotNull List<StaticPartGenerator> staticPartGenerators =
			new ArrayList<StaticPartGenerator>();

	public DefaultStaticPartsGenerator()
  {
	  super();
	  
	  setComponentSeparator(DOUBLE_LINE_SEPARATOR);
  }

	/**
	 * Aggregates and returns the results of
	 * <ul>
	 *   <li>{@link #getStaticPartGenerators()}</li>
	 * </ul>
	 * in the order listed above.
	 *
	 * @see de.jmda.gen.CompoundGenerator#getGeneratorComponents()
	 */
	@Override
	@NotNull
	public List<Generator> getGeneratorComponents()
  {
		// copy specific generators to non-specific generators and make Java happy
		List<Generator> result = new ArrayList<Generator>();
		
		result.addAll(getStaticPartGenerators());

		return result;
  }

	@Override
	@NotNull
  public List<StaticPartGenerator> getStaticPartGenerators()
  {
		return staticPartGenerators;
  }

	public void setStaticPartGenerators(
			@NotNull List<StaticPartGenerator> generators)
  {
  	this.staticPartGenerators = notNull(generators);
  }

	/**
	 * Convenience method to add an <code>StaticPartGenerator</code> to {@link
	 * #getStaticPartGenerators()}.
	 *
	 * @param staticPartGenerator
	 */
	public void add(StaticPartGenerator staticPartGenerator)
	{
		getStaticPartGenerators().add(staticPartGenerator);
	}

	private List<StaticPartGenerator> notNull(List<StaticPartGenerator> generators)
  {
		if (generators == null)
		{
			generators = new ArrayList<StaticPartGenerator>();
		}

		return generators;
  }

	/**
	 * @NotNull
	 * @see de.jmda.gen.java.StaticPartsGenerator#demandPrimaryStaticPartGenerator()
	 */
	@Override
  public StaticPartGenerator demandPrimaryStaticPartGenerator()
  {
		StaticPartGenerator result;

		List<StaticPartGenerator> staticPartGenerators = getStaticPartGenerators();
		
		if (staticPartGenerators.size() == 0)
		{
			result = new DefaultStaticPartGenerator();
			staticPartGenerators.add(result);
		}
		else
		{
			result = staticPartGenerators.get(0);
		}
		
	  return result;
  }
}